package com.ashokvarma.bottomnavigation;

import android.animation.Animator;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.ColorStateList;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.StateListDrawable;
import android.os.Build;
import android.os.CountDownTimer;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.CallSuper;
import androidx.core.content.ContextCompat;
import androidx.core.graphics.drawable.DrawableCompat;

import com.ashokvarma.bottomnavigation.utils.TimeUtils;
import com.ashokvarma.bottomnavigation.utils.Utils;

import java.util.concurrent.TimeUnit;

/**
 * Class description
 *
 * @author ashokvarma
 * @version 1.0
 * @see FrameLayout
 * @since 19 Mar 2016
 */
abstract class BottomNavigationTab extends FrameLayout implements Animator.AnimatorListener {

    protected boolean isNoTitleMode;

    protected int paddingTopActive;
    protected int paddingTopInActive;

    protected int mPosition;
    protected int mActiveColor;
    protected int mInActiveColor;
    protected int mBackgroundColor;
    protected int mActiveWidth;
    protected int mInActiveWidth;

    protected Drawable mCompactIcon;
    protected Drawable mCompactInActiveIcon;
    protected boolean isInActiveIconSet = false;
    protected boolean alrStartCountDownTime = false;
    private boolean mIsWrapFrame = false; //item是否为自适应宽高
    protected String mLabel;
    protected String targetTitle, startTitle, changeTile;
    protected TextView targetView;
    protected long countDownTime;
    protected CountDownTimer timerTask, countDownTimer;


    protected BadgeItem badgeItem;

    boolean isActive = false;

    View containerView;
    TextView labelView;
    TextView iconLabelView;
    TextView countDownTimeView;
    ImageView iconView;
    FrameLayout iconContainerView;
    BadgeTextView badgeView;
    private ObjectAnimator fadeOutAnim, fadeInAnim;

    public BottomNavigationTab(Context context) {
        this(context, null);
    }

    public BottomNavigationTab(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public BottomNavigationTab(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public BottomNavigationTab(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        init();
    }

    void init() {
        setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT));
    }

    public void setIsNoTitleMode(boolean isNoTitleMode) {
        this.isNoTitleMode = isNoTitleMode;
    }

    public boolean getIsNoTitleMode() {
        return isNoTitleMode;
    }

    public void setActiveWidth(int activeWidth) {
        mActiveWidth = activeWidth;
    }

    public void setInactiveWidth(int inactiveWidth) {
        mInActiveWidth = inactiveWidth;
        ViewGroup.LayoutParams params = getLayoutParams();
        params.width = mInActiveWidth;
        setLayoutParams(params);
    }

    public void setIcon(Drawable icon) {
        mCompactIcon = DrawableCompat.wrap(icon);
    }

    public void setInactiveIcon(Drawable icon) {
        mCompactInActiveIcon = DrawableCompat.wrap(icon);
        isInActiveIconSet = true;
    }

    public void setIsWrapFrame(boolean isWrapFrame) {
        this.mIsWrapFrame = isWrapFrame;
    }

    public void setLabel(String label) {
        mLabel = label;
        labelView.setText(label);
    }

    public void setActiveColor(int activeColor) {
        mActiveColor = activeColor;
    }

    public int getActiveColor() {
        return mActiveColor;
    }

    public void setInactiveColor(int inActiveColor) {
        mInActiveColor = inActiveColor;
        labelView.setTextColor(inActiveColor);
    }

    public void setItemBackgroundColor(int backgroundColor) {
        mBackgroundColor = backgroundColor;
    }

    public void setPosition(int position) {
        mPosition = position;
    }

    public void setBadgeItem(BadgeItem badgeItem) {
        this.badgeItem = badgeItem;
    }

    public int getPosition() {
        return mPosition;
    }

    public void select(boolean setActiveColor, int animationDuration) {
        isActive = true;

        ValueAnimator animator = ValueAnimator.ofInt(containerView.getPaddingTop(), paddingTopActive);
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator valueAnimator) {
                containerView.setPadding(containerView.getPaddingLeft(),
                        (Integer) valueAnimator.getAnimatedValue(),
                        containerView.getPaddingRight(),
                        containerView.getPaddingBottom());
            }
        });
        animator.setDuration(animationDuration);
        animator.start();

        iconView.setSelected(true);
        if (setActiveColor) {
            labelView.setTextColor(mActiveColor);
        } else {
            labelView.setTextColor(mBackgroundColor);
        }

        if (badgeItem != null) {
            badgeItem.select();
        }
    }

    public void unSelect(boolean setActiveColor, int animationDuration) {
        isActive = false;

        ValueAnimator animator = ValueAnimator.ofInt(containerView.getPaddingTop(), paddingTopInActive);
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator valueAnimator) {
                containerView.setPadding(containerView.getPaddingLeft(),
                        (Integer) valueAnimator.getAnimatedValue(),
                        containerView.getPaddingRight(),
                        containerView.getPaddingBottom());
            }
        });
        animator.setDuration(animationDuration);
        animator.start();

        labelView.setTextColor(mInActiveColor);
        iconView.setSelected(false);

        if (badgeItem != null) {
            badgeItem.unSelect();
        }
    }

    /**
     * 开启订单tab动效，每5秒切换到新状态
     *
     * @param startTitle
     * @param returnPoints
     * @param countDownTime 单位秒
     */
    public void startOrderAnimation(String startTitle, String returnPoints, long countDownTime) {
        resetContinueBuyData();
        targetTitle = startTitle;
        this.startTitle = startTitle;
        this.countDownTime = countDownTime;
        targetView = labelView;
        //开启连单时的icon
        mCompactIcon = ContextCompat.getDrawable(getContext(), R.drawable.ic_tab_home_sequental_order_press);
        mCompactInActiveIcon = ContextCompat.getDrawable(getContext(), R.drawable.ic_tab_home_sequental_order);

        //小于7天文字变红
        if (TimeUtils.INSTANCE.isLessThanSeven(countDownTime)) {
            setActiveColor(ContextCompat.getColor(getContext(), R.color.tab_select_color));
            setInactiveColor(ContextCompat.getColor(getContext(), R.color.tab_select_color));
        } else {
            setActiveColor(ContextCompat.getColor(getContext(), R.color.tab_color));
            setInactiveColor(ContextCompat.getColor(getContext(), R.color.tab_color));
        }

        //设置返利金额
        iconLabelView.setVisibility(VISIBLE);
        iconLabelView.setText(returnPoints);

        initialise(true);

        labelView.setText(targetTitle);
        //设置view动效
        setViewAlphaAnim(targetView);

        if (timerTask != null)
            timerTask.cancel();
        timerTask = new CountDownTimer(Integer.MAX_VALUE, 5000L + 1000L) {
            @Override
            public void onTick(long millisUntilFinished) {
                fadeOutAnim.start();
            }

            @Override
            public void onFinish() {

            }
        };
        timerTask.start();
        //如果不足一天则开始倒计时显示
        if (countDownTime <= 24 * 60 * 60) {
            alrStartCountDownTime = true;
            starCountDownTimer(countDownTime);
        } else {
            alrStartCountDownTime = false;
            this.changeTile = getChangeTile(countDownTime);
        }

    }

    /**
     * 显示格式为：x天内
     *
     * @param countDownTime 单位秒
     * @return
     */
    private String getChangeTile(long countDownTime) {
        long day = TimeUnit.MILLISECONDS.toDays(countDownTime * 1000);
        return day + "天内";

    }

    /**
     * 开始连单倒计时
     *
     * @param millisInFuture
     */
    private void starCountDownTimer(long millisInFuture) {
        countDownTimeView.setAlpha(0f);
        if (countDownTimer != null)
            countDownTimer.cancel();
        countDownTimer = new CountDownTimer(millisInFuture * 1000, 1000L) {
            @Override
            public void onTick(long millisUntilFinished) {
                countDownTimeView.setText(TimeUtils.INSTANCE.millis2FitTimeSpan(millisUntilFinished));
            }

            @Override
            public void onFinish() {
                countDownTime = 0L;
                resetContinueBuyData();
            }
        };
        countDownTimer.start();
    }


    @Override
    public void onAnimationStart(Animator animation) {

    }

    @Override
    public void onAnimationEnd(Animator animation) {
        //倒计时开始
        if (alrStartCountDownTime) {
            targetView = targetView == labelView ? countDownTimeView : labelView;
            setViewAlphaAnim(targetView);
            fadeInAnim.start();
        } else {
            targetTitle = targetTitle.equals(startTitle) ? changeTile : startTitle;
            targetView.setText(targetTitle);
            fadeInAnim.start();
        }
    }

    @Override
    public void onAnimationCancel(Animator animation) {

    }

    @Override
    public void onAnimationRepeat(Animator animation) {

    }

    private void setViewAlphaAnim(View view) {
        fadeOutAnim = ObjectAnimator.ofFloat(view, "alpha", 1f, 0f);
        fadeOutAnim.setDuration(1000).addListener(this);
        fadeInAnim = ObjectAnimator.ofFloat(view, "alpha", 0f, 1f);
        fadeInAnim.setDuration(1000);
    }

    /**
     * 重置连单状态
     */
    public void resetContinueBuyData() {
        if (timerTask != null)
            timerTask.cancel();
        if (fadeOutAnim != null)
            fadeOutAnim.cancel();
        if (fadeInAnim != null)
            fadeInAnim.cancel();
        if (countDownTimer != null)
            countDownTimer.cancel();
        alrStartCountDownTime = false;
        targetView = labelView;
        mCompactIcon = ContextCompat.getDrawable(getContext(), R.drawable.ic_tab_home_order_press);
        mCompactInActiveIcon = ContextCompat.getDrawable(getContext(), R.drawable.ic_tab_home_order);
        labelView.setVisibility(VISIBLE);
        labelView.setText("连单");
        setActiveColor(ContextCompat.getColor(getContext(), R.color.tab_color));
        setInactiveColor(ContextCompat.getColor(getContext(), R.color.tab_color));
        labelView.setTextColor(ContextCompat.getColor(getContext(),R.color.tab_color));
        countDownTimeView.setAlpha(0);
        iconLabelView.setVisibility(GONE);
        initialise(true);
        //恢复选中状态
        iconView.setSelected(isActive);
    }

    @CallSuper
    public void initialise(boolean setActiveColor) {
        iconView.setSelected(false);
        if (isInActiveIconSet) {
            StateListDrawable states = new StateListDrawable();
            states.addState(new int[]{android.R.attr.state_selected},
                    mCompactIcon);
            states.addState(new int[]{-android.R.attr.state_selected},
                    mCompactInActiveIcon);
            states.addState(new int[]{},
                    mCompactInActiveIcon);
            iconView.setImageDrawable(states);
        } else {
            if (setActiveColor) {
                DrawableCompat.setTintList(mCompactIcon, new ColorStateList(
                        new int[][]{
                                new int[]{android.R.attr.state_selected}, //1
                                new int[]{-android.R.attr.state_selected}, //2
                                new int[]{}
                        },
                        new int[]{
                                mActiveColor, //1
                                mInActiveColor, //2
                                mInActiveColor //3
                        }
                ));
            } else {
                DrawableCompat.setTintList(mCompactIcon, new ColorStateList(
                        new int[][]{
                                new int[]{android.R.attr.state_selected}, //1
                                new int[]{-android.R.attr.state_selected}, //2
                                new int[]{}
                        },
                        new int[]{
                                mBackgroundColor, //1
                                mInActiveColor, //2
                                mInActiveColor //3
                        }
                ));
            }
            iconView.setImageDrawable(mCompactIcon);
        }

        if (isNoTitleMode) {
            labelView.setVisibility(GONE);

            FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) iconContainerView.getLayoutParams();
            layoutParams.gravity = Gravity.CENTER;
            setNoTitleIconContainerParams(layoutParams);
            iconContainerView.setLayoutParams(layoutParams);

            FrameLayout.LayoutParams iconLayoutParams = (FrameLayout.LayoutParams) iconView.getLayoutParams();
            setNoTitleIconParams(iconLayoutParams);
            iconView.setLayoutParams(iconLayoutParams);
        }
        //设置是否自适应宽高
        if (mIsWrapFrame) {
            FrameLayout.LayoutParams iconLayoutParams = (FrameLayout.LayoutParams) iconView.getLayoutParams();
            iconLayoutParams.height = LayoutParams.WRAP_CONTENT;
            iconLayoutParams.width = LayoutParams.WRAP_CONTENT;
            iconLayoutParams.setMargins(0, Utils.dp2px(getContext(), -9f), 0, 0);
            iconView.setLayoutParams(iconLayoutParams);
        }
    }

    protected abstract void setNoTitleIconContainerParams(FrameLayout.LayoutParams layoutParams);

    protected abstract void setNoTitleIconParams(FrameLayout.LayoutParams layoutParams);

}
